package cn.tedu.contorller;

import cn.tedu.dao.ProductDao;
import cn.tedu.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@MultipartConfig
@WebServlet("/SendServlet")
public class SendServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取send.html中的parameter
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String intro = request.getParameter("intro");
        String categoryId = request.getParameter("tagId");

        Part part = request.getPart("file");
        String str = part.getHeader("Content-disposition");
        String suffix = str.substring(str.lastIndexOf("."),str.length()-1);
        //设置图片唯一名字
        String fileName = UUID.randomUUID()+suffix;
        //获取图片保存根目录地址
        String localPath = "E:/IDEATomcat8.5/apache-tomcat-8.5.45/webapps/imgs";
        //设置日期模板
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        //设置图片保存路径
        String dirPath = localPath+format.format(new Date());
        //创建文件夹
        File file = new File(dirPath);
        file.mkdirs();

        //保存图片
        part.write(dirPath+fileName);

        //设置图片访问路径
        String urlPath = "http://localhost:8080/imgs"+format.format(new Date())+fileName;

        ProductDao dao = new ProductDao();
        dao.insert(new Product(0,title,author,intro,Integer.parseInt(categoryId),urlPath));
        response.sendRedirect(request.getContextPath()+"/HomeServlet");
    }

}
